<template>
  <div>
    <!-- 市场列表（独立数据） -->
    <div v-if="modelValue === 0" class="market-block">
      <!-- 标题栏 -->
      <div class="market-header">
        <span class="market-title">热门排行榜</span>
        <span class="market-more" @click="goToQuote">更多</span>
      </div>

      <!-- 直接渲染，无动画 -->
      <div class="list-wrapper">
        <div
          v-for="item in localCoinList"
          :key="item.id"
          class="market-card"
          @click="goToQuantContractShow(item)"
        >
          <div class="icon-wrapper">
            <img
              class="market-coin-icon"
              :src="item.logo"
              @error="e => e.target.src = `https://dummyimage.com/56x56/f5f5f5/888888&text=${item.coinUpperCase[0]}`"
            />
          </div>

          <div class="market-coin-info">
            <div>
              <span class="market-coin-name">{{ item.coinUpperCase }}</span>
              <span class="market-coin-unit">/USD</span>
            </div>
            <div class="market-card-right">
              <div class="market-line-wrap">
                <svg width="160" height="30" viewBox="0 0 160 30">
                  <polyline
                    fill="none"
                    :stroke="getChangeUp(item) ? '#00b386' : '#e74a5e'"
                    stroke-width="1"
                    :points="item.line"
                  />
                </svg>
              </div>
              <div style="text-align: right">
                <div
                  class="market-price"
                  :style="{ color: priceColors[item.coin] || '#8f9693' }"
                  :class="{ flash: priceFlash[item.coin] }"
                >
                  {{ priceFormat(tradeStore.allCoinPriceInfo[item.coin]?.close) }}
                </div>
                <div
                  class="market-rate"
                  :style="{ background: getChangeUp(item) ? '#00b386' : '#e74a5e' }"
                >
                  {{ getChangeUp(item) ? '+' : '-' }}
                  {{ tradeStore.allCoinPriceInfo[item.coin]?.priceChangePercent }}%
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 插槽区（期权第二部分） -->
    <div v-if="modelValue === 1" class="market-block">
      <slot name="currency-card-list"></slot>
    </div>

    <!-- ================= 新闻区块（改成 Coindesk 样式） ================= -->
    <div class="news-block">
      <div class="market-header">
        <span class="market-title">最新资讯</span>
        <span class="market-more" @click="goToNews">更多</span>
      </div>

     <div class="news-list">
       <div
         v-for="news in newsList"
         :key="news.id"
         class="news-item-intl"
         @click="goToNews"
       >
         <div class="news-left-line"></div>
     
         <div class="news-content">
           <div class="rss-time">
             <span class="dot"></span>
             {{ news.time }}
           </div>
     
           <div class="rss-title">{{ news.title }}</div>
     
           <div class="rss-desc">{{ news.desc }}</div>
         </div>
       </div>
     </div>
</div>
  </div>
</template>


<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import axios from "axios"
import { useTradeStore } from '@/store/trade/index'
import { priceFormat } from '@/utils/decimal.js'

const tradeStore = useTradeStore()
const router = useRouter()

const props = defineProps({
  modelValue: Number,
  tabs: Array,
  marketList: Array
})

/* ---------------- 本地币种数据 ---------------- */
const localCoinList = ref([])

/* ---------------- 新闻列表（RSS） ---------------- */
const newsList = ref([])

/* ---------------- 加载 Coindesk RSS ---------------- */
async function loadRSS() {
  const url =
    "https://api.allorigins.win/raw?url=" +
    encodeURIComponent("https://www.coindesk.com/arc/outboundfeeds/rss/")

  const res = await axios.get(url, { responseType: "text" })
  return parseRSS(res.data)
}

function parseRSS(xmlText) {
  const parser = new DOMParser()
  const xml = parser.parseFromString(xmlText, "application/xml")
  const items = [...xml.querySelectorAll("item")].slice(0, 5)

  return items.map((item) => ({
    id: item.querySelector("guid")?.textContent || Date.now(),
    title: item.querySelector("title")?.textContent || "",
    desc: item.querySelector("description")?.textContent || "",
    time: formatPubDate(item.querySelector("pubDate")?.textContent || ""),
  }))
}

function formatPubDate(pubDate) {
  const d = new Date(pubDate)
  if (isNaN(d)) return ""

  const Y = d.getFullYear()
  const M = String(d.getMonth() + 1).padStart(2, "0")
  const D = String(d.getDate()).padStart(2, "0")
  const h = String(d.getHours()).padStart(2, "0")
  const m = String(d.getMinutes()).padStart(2, "0")
  const s = String(d.getSeconds()).padStart(2, "0")

  return `${Y}-${M}-${D} ${h}:${m}:${s}`
}

async function loadNews() {
  try {
    newsList.value = await loadRSS()
  } catch (err) {
    console.error("加载 RSS 新闻失败：", err)
  }
}

/* ---------------- 价格变色闪烁逻辑（保持原样） ---------------- */
const prevPrices = ref({})
const priceColors = ref({})
const priceFlash = ref({})
let colorTimeouts = {}

function setupPriceWatchers() {
  localCoinList.value.forEach(item => {
    if (prevPrices.value[item.coin] !== undefined) return
    watch(
      () => tradeStore.allCoinPriceInfo[item.coin]?.close,
      (newP, oldP) => {
        if (!newP) return
        if (!oldP) {
          prevPrices.value[item.coin] = newP
          priceColors.value[item.coin] = '#8f9693'
          return
        }

        const isUp = newP > oldP
        const isDown = newP < oldP
        priceColors.value[item.coin] = isUp ? '#00b386' : isDown ? '#e74a5e' : '#8f9693'

        priceFlash.value[item.coin] = true
        setTimeout(() => (priceFlash.value[item.coin] = false), 350)

        if (colorTimeouts[item.coin]) clearTimeout(colorTimeouts[item.coin])
        colorTimeouts[item.coin] = setTimeout(() => {
          if (Math.abs(newP - prevPrices.value[item.coin]) < 1e-6) {
            priceColors.value[item.coin] = '#8f9693'
          }
        }, 800)

        prevPrices.value[item.coin] = newP
      },
      { immediate: true }
    )
  })
}
/* ---------------- 涨跌判断 ---------------- */
function getChangeUp(item) {
  const info = tradeStore.allCoinPriceInfo[item.coin]
  return info && Number(info.close) >= Number(info.openPrice)
}

/* ---------------- 跳转 ---------------- */
function goToQuote() {
  router.push({ path: '/quote' })
}
function goToNews() {
  router.push({ path: '/news' })
}
function goToNewsDetail(id) {
  router.push({ path: '/news/detail', query: { id } })
}
function goToQuantContractShow(item) {
  router.push({
    path: '/quantContract',
    query: { id: item.id, symbol: item.coin }
  })
}

/* ---------------- 加载行情列表（保持原样） ---------------- */
function shuffleArray(arr) {
  const a = arr.slice()
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[a[i], a[j]] = [a[j], a[i]]
  }
  return a
}

function genRandomPoints(count = 100, width = 150, height = 28) {
  const step = width / (count - 1)
  let value = Math.random() * height
  const points = []
  for (let i = 0; i < count; i++) {
    value += (Math.random() - 0.5) * (height / 5)
    value = Math.min(Math.max(value, 0), height)
    points.push(`${i * step},${height - value}`)
  }
  return points.join(' ')
}

async function loadPageCoinList() {
  if (tradeStore.getSecondContractCoinList) {
    await tradeStore.getSecondContractCoinList()
  }
  const allList = tradeStore.secondContractCoinList || []
  const onlyType2 = allList.filter(it => Number(it.coinType) === 2)
  const randomList = shuffleArray(onlyType2).slice(0, 5)

  localCoinList.value = randomList.map(c => ({
    ...c,
    line: genRandomPoints()
  }))

  setupPriceWatchers()
}

let refreshTimer = null

/* ---------------- 生命周期 ---------------- */
onMounted(async () => {
  await loadPageCoinList()
  refreshTimer = setInterval(loadPageCoinList, 10000)

  loadNews()  // 读取RSS
})

onBeforeUnmount(() => {
  if (refreshTimer) clearInterval(refreshTimer)
  Object.values(colorTimeouts).forEach(clearTimeout)
  colorTimeouts = {}
})

watch(
  () => props.modelValue,
  async (newVal) => {
    if (newVal === 0) {
      await nextTick()
      await loadPageCoinList()
    }
  }
)
</script>


<style scoped>
/* 通用区块 */
.market-block,
.news-block {
  background: #f6f7f8;
  border-radius: 18px;
  padding: 0;
  margin-bottom: 24px;
}

/* 标题栏 */
.market-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0px 8px;
  font-size: 23px;
  font-weight: 600;
  color: #222;
}

.market-title { font-weight: 700; }
.market-more {
  font-size: 13px;
  color: #999;
  cursor: pointer;
}
.market-more:hover { color: #666; }

/* 行情卡片 */
.market-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 5px 0;
}

/* 图标固定容器（关键！防止左移） */
.icon-wrapper {
  width: 38px;
  height: 38px;
  margin-left: 8px;
  flex-shrink: 0;
  border-radius: 50%;
  overflow: hidden;
  
  display: flex;
  align-items: center;
  justify-content: center;
}

.market-coin-icon {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 50%;
}

.market-coin-name {
  color: #111;
  font-weight: bold;
  font-size: 14px;
}

.market-coin-unit {
  color: #888;
  font-size: 12px;
  margin-left: 4px;
}

.market-card-right {
  width: 280px;
  background: #fff;
  border-radius: 14px;
  padding: 8px 18px 8px 8px;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
}

.market-line-wrap {
  height: 32px;
  width: 120px;
}

.market-price {
  font-size: 15px;
  font-weight: 600;
  transition: color 0.15s;
}

.market-rate {
  color: #fff;
  font-size: 13px;
  border-radius: 6px;
  padding: 2px 16px;
  margin-top: 4px;
}

/* 列表容器 */
.list-wrapper {
  padding: 0 0px 0px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 价格闪烁（保留） */
.flash {
  animation: priceFlashAnim 0.35s ease-out;
}
@keyframes priceFlashAnim {
  0% { opacity: 0.6; transform: scale(1); }
  40% { opacity: 1; transform: scale(1.12); }
  100% { opacity: 1; transform: scale(1); }
}

/* 新闻列表 */
.news-list {
    
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.news-item {
  background: #fff;
  border-radius: 12px;
  padding: 12px 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.news-item:hover {
  background: #f9f9f9;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.news-title {
  font-size: 14px;
  color: #111;
  font-weight: 500;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.news-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
/* ================= RSS 新闻样式 ================= */

.news-item-rss {
  background: #fff;
  border-radius: 14px;
  padding: 14px 16px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  transition: all 0.2s ease;
}

.news-item-rss:hover {
  background: #fafafa;
  transform: translateY(-2px);
}

.rss-time {
  font-size: 12px;
  color: #777;
  display: flex;
  align-items: center;
  gap: 6px;
}

.dot {
  width: 8px;
  height: 8px;
  background: #ffcc00;
  border-radius: 50%;
}

.rss-title {
  font-size: 15px;
  font-weight: 700;
  color: #111;
  margin-top: 6px;
  line-height: 1.5;
}

.rss-desc {
  margin-top: 4px;
  font-size: 13px;
  color: #666;
  line-height: 1.45;
}
/* ======= 国际资讯风格（与截图完全一致）======= */

.news-item-intl {
  
  border-radius: 14px;
  padding: 14px 16px;
  display: flex;
  gap: 12px;
  position: relative;
  cursor: pointer;

  transition: all 0.2s ease;
}

.news-item-intl:hover {
  background: #fafafa;
  transform: translateY(-2px);
}

/* 左侧竖线 */
.news-left-line {
  width: 3px;
  background: #ddd;
  border-radius: 3px;
}

/* 新闻主体 */
.news-content {
  flex: 1;
}

/* 时间行 */
.rss-time {
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 6px;
}

.dot {
  width: 8px;
  height: 8px;
  background: #ffcc00;
  border-radius: 50%;
}

/* 标题 */
.rss-title {
  font-size: 15px;
  font-weight: 700;
  color: #111;
  margin-top: 6px;
  line-height: 1.45;
}

/* 摘要 */
.rss-desc {
  margin-top: 4px;
  font-size: 13px;
  color: #555;
  line-height: 1.45;
}

</style>